<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/13
 * Time: 15:09
 */


namespace app\admin\controller;

use app\admin\model\UserModel;
use app\admin\model\ViplevelModel;
use mg_api\Mg_api;
use think\Controller;
use think\Db;
use think\Validate;
use think\Loader;
use wechat\wechatCallbackapiTest;


//客户控制器、
class User extends Base
{

    //客户列表
    public function userlist()
    {
       $condition_type =  $this->request->param('condition_type');
        $condition_val = $this->request->param('condition_val');
        $start_subscribe = $this->request->param('start_subscribe');
        $end_subscribe = $this->request->param('end_subscribe');
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');
        $is_subscribe = $this->request->param('subscribe');
        //条件
        $condition = [
            'condition_type'=>$condition_type??'',
            'condition_val'=>$condition_val??'',
            'start_subscribe'=>$start_subscribe??"",
            'end_subscribe'=>$end_subscribe??'',
            'start_time'=>$start_time??'',
            'end_time'=>$end_time??'',
            'subscribe'=>$is_subscribe??null
        ];

        $model = Db::table('dx_user');
        if($condition_type){
            switch($condition_type){
                case 'nickname':
                    $items = $model->where('nick_name','like',"%$condition_val%")
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('nick_name','like',"%$condition_val%")->count();
                    break;
                case "user_name":
                    $items = $model->where('user_name','like',"%$condition_val%")
                        ->order('time desc')
                        ->paginate(10);
                   $count = Db::table('dx_user')->where('user_name','like',"%$condition_val%")->count();
                    break;
                case "user_sex":
                    if($condition_val == '男'){
                        $sex = 1;
                    }elseif($condition_val == '女'){
                        $sex = 0;
                    }else{
                        $sex = null;
                    }
                    $items = $model->where('user_sex',"$sex")
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('user_sex',"$sex")->count();
                    break;
                case "companyname":
                    $items = $model->where('companyname','like',"%$condition_val%")
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('companyname','like',"%$condition_val%")->count();
                    break;
                case "user_tel":

                    $items = $model->where('user_tel',"$condition_val")
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('user_tel',"$condition_val")->count();
                    break;
                case "subscribe":
                    $items = $model->where('subscribe',"$is_subscribe")
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('subscribe',"$is_subscribe")->count();
                    break;
                case "time":
                    //转换为 时间戳
                    $start = strtotime($start_time);
                    $end = strtotime($end_time);

                    $items = $model->where('time','>',$start)
                        ->where('time','<',$end)
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('time','>',$start)
                        ->where('time','<',$end)->count();
                    break;
                case "subscribe_time":
                    //转换为 时间戳
                    $start = strtotime($start_subscribe);
                    $end = strtotime($end_subscribe);
                    $items = $model->where('subscribe_time','>',$start)
                        ->where('subscribe_time','<',$end)
                        ->order('time desc')
                        ->paginate(10);
                    $count = Db::table('dx_user')->where('subscribe_time','>',$start)
                        ->where('subscribe_time','<',$end)->count();
                    break;
            }
        }else{
            //查询全部
            $items = $model->order('time desc')
                ->paginate(10);
            $count = Db::table('dx_user')->count();
        }
        $arr = [];
            foreach ($items as $k => $v) {
                //获取总积分
                if ($v['is_pass'] == '1') {
                    $mg_api = new Mg_api();
                    $api_data = [
                        'key' => "Get_LinkMan_Point",
                        'wx_openid' => $v['openid'],
                    ];
                    $api_re = $mg_api->api($api_data);
                    $api_re = json_decode($api_re, true);
                    $jifen = $api_re['JData']['0']['point'];
                    $jifen = $jifen / 50;
                    if ($jifen) {
                        $data = $this->viplevel($jifen);

                        if (isset($data)) {
                            $re = $data->title;
                        } else {
                            $re = '<span style="color: red">暂无等级</span>';
                        }
                    } else {
                        $re = '<span style="color: red">暂无等级</span>';
                    }
                } else {
                    $re = '没有绑定档案';
                    $jifen = '没有绑定档案';
                }
                $arr[$k] = $items[$k];
                $arr[$k]['vip'] = $re;
                $arr[$k]['jifen'] = $jifen;
            }
        $this->assign('condition', $condition);
        $this->assign('count', $count);
        $this->assign('page', $items->render());
        $this->assign('items', $arr);
        return view('list');

    }

    //修改客户资料
    public function edit()
    {
        if (!empty($_POST)) {
            $yanzheng = [
                'user_name' => 'require',
                'user_tel' => 'number|length:11',
            ];
            $msg = [
                'user_name.require' => '昵称名不能为空',
                'user_tel.number' => '客户电话必须为数字',
                'user_tel.length' => '客户电话必须为11数',
            ];
            $validate = new Validate($yanzheng, $msg);
            $data = [
                'user_name' => $_POST['user_name'],
                'user_sex' => $_POST['user_sex'],
                'user_tel' => $_POST['user_tel'],
                'position' => $_POST['position'],
                'company' => $_POST['company'],
                'user_id' => $_POST['user_id'],
                'is_pass' => $_POST['is_pass'],
                'companyname' => $_POST['companyname'],
                'company_id' => $_POST['companyname_coding'],
                'time' => time()
            ];
            $re = $validate->check($data);
            if (!$re) {
                $this->error($validate->getError());
            } else {

                $re = Db::table('dx_user')->update($data);
                if ($re) {
                    $user =UserModel::get($_POST['user_id']);
                  if($user->is_pass == 1){
                      //推送通过消息
                      $wechat = new wechatCallbackapiTest();
                      $ee = $wechat->send_msg('您已通过优家舒适圈的审核，欢迎您的加入！',$user->openid);
                  }
                    $this->success('修改成功', url('admin/user/userlist'), 2);
                } else {
                    $this->error('修改失败', url('admin/user/userlist'), 2);
                }
            }
        } else {
            $user_id = input('param.user_id');
            $data = Db::name('user')->where('user_id', "$user_id")->find();
            $this->assign('data', $data);
            return view('edit');
        }
    }
    //添加用户
    public function add()
    {
        //查询客服
        $ser = Db::name('service')->field('ser_id,ser_name')->select();
        $this->assign('ser', $ser);
        return view('tianjia');
    }
    //添加用户表单接受
    public function addform()
    {
        $yanzheng = [
            'user_name' => 'require',
            'user_tel' => 'number|length:11',
            'user_dizhi' => 'require',
        ];
        $msg = [
            'user_name.require' => '客户名不能为空',
            'user_tel.number' => '客户电话必须为数字',
            'user_tel.length' => '客户电话必须为11数',

        ];
        $date = [
            'user_name' => $_POST['user_name'],
            'turename' => $_POST['turename'],
            'user_sex' => $_POST['user_sex'],
            'user_tel' => $_POST['user_tel'],
            'ser_id' => $_POST['ser_id'],
            'edit_time' => date('Y-m-d H:i:s'),
            'register_time' => date('Y-m-d H:i:s', time()),
        ];
        $validate = new Validate($yanzheng, $msg);
        $re = $validate->check($date);

        if (!$re) {

            $this->error($validate->getError());
        } else {
            $re = Db::table('dx_user')->insert($date);
            if ($re) {
                $this->success('添加成功', url('admin/user/userlist'), 2);
            } else {
                $this->error('添加失败，请稍后重试');
            }
        }
    }

    //删除客户
    public function del()
    {
        Db::startTrans();
        try {
            $opinion = Db::table('opinion')->where('user_id', $_POST['userid'])->select();
            Db::table('dx_user')->delete($_POST['userid']);
            Db::table('project')->where('user_id', $_POST['userid'])->delete();
            Db::table('integral')->where('user_id', $_POST['userid'])->delete();
            if ($opinion) {
                foreach ($opinion as $k => $v) {
                    Db::table('reply')->where('opinion_id', $v['id'])->delete();
                }
                $opinion = Db::table('opinion')->where('user_id', $_POST['userid'])->delete();
            }
            // 提交事务
            echo '1';
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            echo "0";
            Db::rollback();
        }
    }

    //查询
    public function chaxun()
    {
        //echo $_POST['data'];
        $re = Db::name('user')->where('user_tel', $_POST['data'])->find();
        $re1 = Db::name('user')->where('turename', $_POST['data'])->find();
        if ($re == false and $re1 == false) {
            echo '没有找到该用户';
        } else {
            if ($re) {
                echo $re['user_id'];
            } else {
                echo $re1['user_id'];
            }

        }
    }

    public function f($id)
    {

        $items = Db::table('dx_user')
            ->alias('u')
            ->where('user_id', $id)
            ->where('user_tel != ""')
            ->join('dx_service s', 'u.ser_id = s.ser_id', 'LEFT')
            ->field('u.*,s.ser_name')
            ->order('u.edit_time desc')
            // ->select();
            ->paginate(10);
        // var_dump($items);
        $this->assign('page', $items->render());
        $this->assign('items', $items);
        return view('list');
    }


    protected function viplevel($data)
    {
        $viplevel = ViplevelModel::all();
        foreach ($viplevel as $k => $v) {
            if ($data >= $v->range_up and $data < $v->range_down) {
                return $v;
            }
        }

    }

    //发送用户资料；
    public function send_user()
    {
        //获取用户id 并获取用户的资料
        $user_id = $_POST['user_id'];
        //   $user = UserModel::get($user_id);
        $user = Db::name('user')->where('user_id', $user_id)->find();
        $sex = $user['user_sex'] == 1 ? '男' : '女';
        if ($user['openid'] == '') {
            $this->error('openid不能为空');
        }
        if ($user['user_tel'] == "") {
//            $this->error('电话号码不能为空');
            echo json_encode('电话号码不能为空');
            return;
        }
        $data = [
            'key' => 'add_hzhb',
            'sex' => $sex,
            'F_IntermediaryID' => $user['company_id'],
            'F_Name' => $user['user_name'],
            'F_GW' => $user['position'],
            'F_Tel' => $user['user_tel'],
            'wx_openid' => $user['openid'],
            'address' => "",
            'idcard' => "",
            'birthday' => "",
            'QQ' => "",
            'Bankcode' => "",
            'F_Email' => "",
            'F_Notes' => "",
        ];


        /*  $sex = $user->user_sex == 1 ? '男' : '女';
          if ($user->openid == '') {
              $this->error('openid不能为空');
          }
          if ($user->user_tel == "") {
              $this->error('电话号码不能为空');
          }
          $data = [
              'key' => 'add_hzhb',
              'sex' => $sex,
              'F_IntermediaryID' => $user->company_id,
              'F_Name' => $user->user_name,
              'F_GW' => $user->position,
              'F_Tel' => $user->user_tel,
              'wx_openid' => $user->openid,
              'address' => "",
              'idcard' => "",
              'birthday' => "",
              'QQ' => "",
              'Bankcode' => "",
              'F_Email' => "",
              'F_Notes' => "",
          ];*/

        $mg_api = new Mg_api();
        $re = $mg_api->api($data);
        $re = json_decode($re, true);

        if ($re['Status']) {
            $user_up = Db::name('user')->where('user_id', $user_id)->update([
                "is_pass" => '1'
            ]);
            /*    $user_up = UserModel::get($user_id);
                $user_up->is_pass = '1';
                $user_up->save();*/
            echo json_encode(1);
        } else {
            echo json_encode($re['Message']);
        }
    }

    //动态获取公司
    public function get_cmplist()
    {
        $mg_api = new Mg_api();
        $data = [
            'key' => 'Get_cmpList',
            'keyword' => $_POST['company']
        ];
        $re = $mg_api->api($data);
        echo $re;

    }


    public function test()
    {
        $mg_api = new Mg_api();
        $data = [
            'key' => 'Get_Project_List',
            // 'wx_openid' => 'o2ztkxNweN8QX-84m9How9KnqWBw',
            'wx_openid' => 'o2ztkxNe9Ol9lgD0m0D_kJrb3Yfw',
            'types' => '全部'

        ];
        /* $data = [
             'key' => "Get_LinkMan_Point",
             'wx_openid' => 'o2ztkxNweN8QX-84m9How9KnqWBw',

         ];*/
        /*  $data=[
              'key'=>'Get_Pic',
              'address'=>'出水芙蓉1期36栋1单元5楼36-1-9号'
          ];*/
        $re = $mg_api->api($data);
        $re = json_decode($re, true);
        var_dump($re);
    }
    //使用同一账户
    public function same_account(){
        $ids = $this->request->param('ids');
        $ids =  json_decode($ids, true);
        if($ids){
            foreach($ids as $k=>$v){
                $re = UserModel::where('user_id',$v)->update([
                    'is_test'=>1
                ]);
            }
        }
    }
    //取消设为同一用户
    public function is_test(){
        $id = $this->request->param('id');
        $new_state = $this->request->param('new_state');
        UserModel::where('user_id',$id)->update([
            'is_test'=>$new_state
        ]);
    }
    /*
     * 查询是否有指定用户
     * */
    public function get_zhiding(){
        if(request()->isAjax()){
            $user_id = $this->request->param('user_id');
            $re = Db::table('user_openid')->where('user_id',$user_id)->find();
            if(!$re) return json(['code'=>1,'data'=>'','msg'=>'没有指定用户']);
           $user_zhiding =  UserModel::where('openid',$re['openid'])->find();
            if(!$user_zhiding) return json(['code'=>1,'data'=>'','msg'=>'没有找到指定用户']);
            $data = [
                'name'=>$user_zhiding->user_name,
                'nickname'=>$user_zhiding->nick_name,
            ];
            return json(['code'=>0,'data'=>$data,'msg'=>'成功']);

        }else{
            return json(['code'=>1,'data'=>'','msg'=>'非法请求']);
        }
    }
    /*
     *
     * 绑定用户
     *
     * */
    public function bangding(){
        if(request()->isAjax()){
            $user_id = $this->request->param('user_id');
            $openid = $this->request->param('openid');
            if($openid == ''){
                Db::table('user_openid')->where('user_id',$user_id)->delete();
                return json(['code'=>0,'data'=>'','msg'=>'解除绑定']);
            }else{
                $user_bangding = UserModel::where('openid',$openid)->find();
                if(!$user_bangding) return json(['code'=>1,'data'=>'','msg'=>'没有获取到openid用户']);

                $re = Db::table('user_openid')->insert([
                    'user_id'=>$user_id,
                    'openid'=>$openid
                ]);
                if($re){
                    return json(['code'=>0,'data'=>$re,'msg'=>'成功']);
                }else{
                    return json(['code'=>1,'data'=>'','msg'=>'绑定失败']);

                }
            }

        }else{
            return json(['code'=>1,'data'=>'','msg'=>'非法请求']);

        }
    }
//用户表下载
	public function excel()
    {
       $path = dirname(__FILE__);
       Loader::import('execl.PHPExcel');
       Loader::import('excel.PHPExcel.IOFactory');

       $name = UserModel::SelectAll();   
       $fan = $this -> check($name);
       $PHPExcel = new \PHPExcel();

       $PHPSheet = $PHPExcel -> getActiveSheet();
       $PHPSheet -> setTitle("test");
       $num = count($fan);
      $PHPSheet -> setCellValue('A1','姓名')
                 -> setCellValue('B1','电话号码') 
                 -> setCellValue('C1','性别')
                 -> setCellValue('D1','公司')
                 -> setCellValue('E1','职位')
                 -> setCellValue('F1','是否通过')
                 -> setCellValue('G1','推荐人')
                 -> setCellValue('H1','关注时间')
                 -> setCellValue('I1','创建时间')
                -> setCellValue('J1','昵称');
                 for ($i=0; $i < $num; $i++) { 
                 $N = $i+2;
                 $A = 'A'.$N;
                 $B = 'B'.$N;
                 $C = 'C'.$N;
                 $D = 'D'.$N;
                 $E = 'E'.$N;
                 $F = 'F'.$N;
                 $G = 'G'.$N;
                 $H = 'H'.$N;
                 $I = 'I'.$N;
                 $J = 'J'.$N;

                 $PHPSheet -> setCellValue($A,$fan[$i]['name'])
                           -> setCellValue($B,$fan[$i]['tell']) 
                           -> setCellValue($C,$fan[$i]['sex'])
                           -> setCellValue($D,$fan[$i]['company'])
                           -> setCellValue($E,$fan[$i]['position'])
                           -> setCellValue($F,$fan[$i]['pass'])
                           -> setCellValue($G,$fan[$i]['referee'])
                           -> setCellValue($H,$fan[$i]['subscribe'])
                           -> setCellValue($I,$fan[$i]['time'])
                     -> setCellValue($J,$fan[$i]['nick_name']);
                 }
 
       
       $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");
       header('Content-Disposition: attachment;filename="表单数据.xlsx"');
       header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
       $PHPWriter->save("php://output");

    }

    public function check($array)
    {
        if (is_array($array)) 
        {
            if (empty($array)) 
            {
                $this -> error('传入数组没有值');
            }
            else
            {
                $num = count($array);
                $return = [];
                for($i=0;$i<$num;$i++)
                {
                    $user_name = $array[$i]['user_name'];
                    $user_tell = $array[$i]['user_tel'];
                    $user_sex =  $array[$i]['user_sex'] == '0' ? '女' : '男';
                    $user_comp = $array[$i]['companyname'];
                    $user_posi = $array[$i]['position'];
                    $user_pass = $array[$i]['is_pass'] == '0' ? '未通过' : '已通过';
                    $user_refe = $array[$i]['referee'] == '' ? '没有推荐人' : $array[$i]['referee'];
                    $user_subs = $array[$i]['subscribe_time'] == '' ? '未关注' : date('Y-m-d' , $array[$i]['subscribe_time']);
                    $user_time = date('Y-m-d' , $array[$i]['time']);

                    $return[$i] = [
                                    'name' => $user_name , 
                                    'tell' => $user_tell ,
                                    'sex'  => $user_sex ,
                                    'company' => $user_comp ,
                                    'position' => $user_posi ,
                                    'pass' => $user_pass , 
                                    'referee' => $user_refe ,
                                    'subscribe' => $user_subs ,
                                    'time'  =>  $user_time
                                  ];
                }

                return $return;
                
            }
        }
        else
        {
            $this -> error('传入数据为数组');
        }
    }
	
}